package com.ltmonitor.service;

import com.ltmonitor.vo.JT808MessageVo;
import com.ltmonitor.web.controller.websocket.JT808MessageWebSocketHandler;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;

@Service("jt808MessaagePushService")
public class JT808MessaagePushService implements IJT808MessaagePushService {

	@Resource
	JT808MessageWebSocketHandler jt808MessageWebSocketHandler;
	@Autowired
	protected IVehicleDataService vehicleDataService;

	@Autowired
	protected IBasicDataService basicDataService;

	/**
	 * 终端命令服务
	 */
	@Autowired
	protected ITerminalCommandService terminalCommandService;

	@Autowired
	protected IJT809CommandService jt809CommandService;

	@Autowired
	protected IPlatformStateService platformStateService;

	@Autowired
	protected IAlarmConfigService alarmConfigService;
	@Autowired
	protected IQueryService queryService;

	private static Logger logger = Logger.getLogger(JT808MessaagePushService.class);
	private boolean startUpdate = true;
	/**
	 * 开辟线程，扫描报警记录表，获取最新的报警
	 */
	private Thread processMessageThread;

	Map<String, Date> alarmMap = new HashMap<String, Date>();

	List<JT808MessageVo> jt808MesageList = new ArrayList<JT808MessageVo>();

	private ConcurrentLinkedQueue<JT808MessageVo> dataQueue = new ConcurrentLinkedQueue();
	/**
	 * 通过spring配置，开机自动启动调用此方法，创建线程，在线程中不断的扫描库表
	 */
	@PostConstruct
	public void start() {
		processMessageThread = new Thread(new Runnable() {
			public void run() {
				ProcessMessageThreadFunc();
			}
		});
//		processMessageThread.start();

	}

	@Override
	public void pushMessage(JT808MessageVo am)
	{
		dataQueue.add(am);
	}

	private void ProcessMessageThreadFunc() {
		while (startUpdate) {
			try {
				JT808MessageVo am = null;
				this.jt808MesageList.clear();;
				while ((am = dataQueue.poll()) != null) {
					jt808MesageList.add(am);

				}
				if (this.jt808MesageList.size() > 0) {
					// logger.error("count:"+ jt808MesageList.size());
					jt808MessageWebSocketHandler.broadcast(jt808MesageList);
				}
			}catch (Exception ex)
			{
				logger.error(ex.getMessage(), ex);
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e1) {
				logger.error(e1.getMessage(), e1);
			}
		}
	}

}
